#ifndef SERVER_H
#define SERVER_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QString>
#include <QByteArray>
#include <QDebug>
#include <QMap>
#include <QFile>
#include <QDataStream>
#include <QThread>
#include "virtualfs.h"
#include "pagegenerator.h"
#include "clientthread.h"
#include "clientsdatabase.h"
#include "schedulethread.h"
#include "os_dependence.h"


template <typename T>
class SafeThreadRemover : public QThread
{
private:
  std::vector <T *> items;
  QMutex mtx;

public:
  explicit SafeThreadRemover() {}

  ~SafeThreadRemover() {
      waitForFinished();
  }


  void run()
  {
      while( items.size() )
      {
          //mtx.lock();
          qWarning() << "Safe remove object";
          delete items[0];
          items.erase( items.begin() );
          //mtx.unlock();
      }
  }

  void deleteMe(T *entry)
  {
    waitForFinished();
    //mtx.lock();
    items.push_back(entry);
    QSleep::usleep(100);
    //mtx.unlock();
    start(QThread::LowestPriority);
  }

  void waitForFinished()
  {
      if( this->isRunning() )
          this->wait(100);
  }

};


class Server : public QTcpServer/*, QThread*/
{
    Q_OBJECT
public:
    Server(QObject *parent = 0);
    ~Server();

    int init_host(QHostAddress address, int port);
    int stop();
    const QString & ip() const;
    int port() const;
    inline VirtualFs *getVirtualFs() { return &vfs; }
    void emitLog(const QString & msg, uint color);
    void startClientServerDialog( int handle );
    void incomingConnection(int handle);
    void abort(bool wait = false);
    void force_abort();
    inline ClientsDataBase *clientsDataBase() { return &c_database; }


signals:
    void log(const QString & , uint color = 0);
    void clientConnected( ClientThread *t );
    void clientDisconected( const QString & );
    void UpdateBar();

private slots:
    void clientHasBeenConnected(ClientThread *);
    void clientHasBeenDisconected(ClientThread *);

public slots:
    void connections_lock();
    void connections_unlock();

public:
    VirtualFs vfs;
    PageGenerator pgen;
    ClientsDataBase c_database;
    ScheduleThread scheduler;

protected:
    QMutex mutex;
    QString _ip;
    int _port;
    bool connections_locked;

};




#endif // SERVER_H
